/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.vip.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.entity.Extend;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.msg.SmsUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.vip.entity.*;
import com.jeesite.modules.vip.service.MemberService;
import com.jeesite.modules.vip.service.ProjectService;
import com.jeesite.modules.vip.state.RecordTypeEnum;
import com.jeesite.modules.vip.state.ReviewerEnum;
import com.jeesite.modules.vip.state.VipUserTypeEnum;
import com.jeesite.modules.vip.utils.RecordToExcelUtils;
import com.jeesite.modules.vip.utils.SMSUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.vip.service.RecordService;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * recordController
 * @author xtp
 * @version 2018-08-25
 */
@Controller
@RequestMapping(value = "${adminPath}/vip/record")
public class RecordController extends BaseController {

	@Autowired
	private RecordService recordService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private UserService userService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Record get(String id, boolean isNewRecord) {
		return recordService.get(id, isNewRecord);
	}

	/**
	 * 审核列表
	 */
	@RequiresPermissions("vip:check:view")
	@RequestMapping(value = {"reviewList", ""})
	public String reviewList(Record record, Model model) {
		model.addAttribute("record", record);
        if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
            return "modules/mobile/reviewList";
        }
		return "modules/vip/reviewList";
	}

	/**
	 * 审核通过列表
	 */
	@RequiresPermissions("vip:check-pass:view")
	@RequestMapping(value = {"reviewPassList", ""})
	public String reviewPassList(Record record, Model model) {
		model.addAttribute("record", record);
        //默认现在充值和结账的记录
        record.setType1(StringUtils.isBlank(record.getType1()) ? "2" : "1");
		if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
			return "modules/mobile/reviewPassList";
		}
		return "modules/vip/reviewPassList";
	}

	/**
	 * 审核申请
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = {"review", ""})
	@Transactional(rollbackFor = Exception.class)
	public String review(Record record, Model model,String state) {
		if(RecordTypeEnum.getValue(Integer.parseInt(state))== null){
			return "redirect:reviewList";
		}
		User user = UserUtils.getUser();
		record.setReviewerState(state);
		record.setReviewerId(user.getUserCode());
		recordService.save(record);
		//更新会员数据
		Member member = memberService.get(record.getMemberId());
		member.setRechargeTotal(record.getMoney()+member.getRechargeTotal());
		member.setPoints(record.getMoney()+member.getPoints());
		member.setBalance(record.getMoney()+member.getBalance());
		memberService.save(member);
		return "redirect:reviewList";
	}


	/**
	 * 出货、入货、结账、充值
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = {"goods", ""})
	public String goods(String type,String userId,Model model) {
		Record record = new Record();
		//查找新增记录的用户
		Member member =memberService.get(userId);
		record.setMemberId(member.getId());
		record.setType(type);
		//查找所有项目
		List<Project> projectList;
		//系统管理可以选择所有项目
		if(VipUserTypeEnum.ADMIN.getValue().equals(UserUtils.getUser().getExtend().getExtendS1())){
			projectList = projectService.findList(new Project());
		}else{
			Map map = new HashMap();
			map.put("empCode",UserUtils.getUser().getRefCode());
			projectList = projectService.findAgentProject(map);
		}
		model.addAttribute("member",member);
		model.addAttribute("projectList", projectList);
		model.addAttribute("record",record);
		return "modules/vip/goodsForm";
	}

	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("vip:check:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Record> listData(Record record, HttpServletRequest request, HttpServletResponse response) {
		User currUser = UserUtils.getUser();
		boolean isAdminUser = currUser.isSuperAdmin() || VipUserTypeEnum.ADMIN.getValue().equals(currUser.getExtend().getExtendS1());
		boolean isCheckUser = VipUserTypeEnum.CHECK_USER.getValue().equals(currUser.getExtend().getExtendS1()) ||
					VipUserTypeEnum.FINANCE.getValue().equals(currUser.getExtend().getExtendS1());
		boolean isReadOnlyUser =  VipUserTypeEnum.READONLY_USER.getValue().equals(currUser.getExtend().getExtendS1());
		//不是系统管理员，不是审核人员,或不是只读角色则需要过滤数据
		if(!isAdminUser && !isCheckUser && !isReadOnlyUser){
			User user = new User();
			user.setUserCode(currUser.getUserCode());
			record.setAgentUser(user);
		}
		return recordService.findPage(new Page<Record>(request, response), record);
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = "form")
	public String form(Record record, Model model) {
		model.addAttribute("record", record);
		return "modules/vip/recordForm";
	}

	/**
	 * 保存record
	 */
	@RequiresPermissions("vip:record:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Record record) {
		recordService.save(record);
		return renderResult(Global.TRUE, text("操作成功！"));
	}
	
	/**
	 * 删除record
	 */
	@RequiresPermissions("vip:record:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Record record) {
		recordService.delete(record);
		return renderResult(Global.TRUE, text("删除记录成功！"));
	}


    /**
     * 出货、入货、结账、充值操作
     */
    @RequiresPermissions("vip:record:edit")
    @PostMapping(value = "update")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public String update(@Validated Record record,String memberId) {
        Member member = memberService.get(memberId);
        User user = UserUtils.getUser();
		String checkStatus = ReviewerEnum.UN_CHECK.getValue();
		//出货  减余额、减积分
        if(RecordTypeEnum.OUT.getValue().equals(record.getType())){
            //是否有直接出货权限
			if(UserUtils.getSubject().isPermitted("vip:bussiness:out")){
				member.setPoints(member.getPoints()-record.getMoney());
				member.setBalance(member.getBalance()-record.getMoney());
				member.setOutTotal(member.getOutTotal() + record.getMoney());
				checkStatus = ReviewerEnum.PASS.getValue();
			}
        }
		//入货  加余额、加积分
        if(RecordTypeEnum.IN.getValue().equals(record.getType())){
			//是否有直接入货权限
			if(UserUtils.getSubject().isPermitted("vip:bussiness:in")){
				member.setPoints(member.getPoints()+record.getMoney());
				member.setBalance(member.getBalance()+record.getMoney());
				member.setInTotal(member.getInTotal()+record.getMoney());
				checkStatus = ReviewerEnum.PASS.getValue();
			}
        }
		//结账  余额加或减少、积分加或减少、支出加或减
		if(RecordTypeEnum.CHECKOUT.getValue().equals(record.getType())){
			//是否有直接结账权限
			if(UserUtils.getSubject().isPermitted("vip:bussiness:checkout")){
				member.setPoints(member.getPoints()-record.getMoney());
				member.setBalance(member.getBalance()-record.getMoney());
				member.setPayTotal(member.getPayTotal()+record.getMoney());
				checkStatus = ReviewerEnum.PASS.getValue();
			}
		}
		//充值  加余额、加积分、加总充值
		if (RecordTypeEnum.RECHARGE.getValue().equals(record.getType())){
			//是否有直接结账权限
			if(UserUtils.getSubject().isPermitted("vip:bussiness:recharge")){
				member.setRechargeTotal(record.getMoney()+member.getRechargeTotal());
				member.setPoints(record.getMoney()+member.getPoints());
				member.setBalance(record.getMoney()+member.getBalance());
				checkStatus = ReviewerEnum.PASS.getValue();
			}
		}

		//有交易操作权限的，直接审核通过，并插入审核人id
		String message = "请等待审核!";
		if(ReviewerEnum.PASS.getValue().equals(checkStatus)){
			record.setReviewerId(user.getUserCode());
			message = "";
		}
		record.setReviewerState(checkStatus);
		record.setBalance(member.getBalance());
        memberService.save(member);
        recordService.save(record);
        //需要审核，发送审核通知给审核员或财务
        if(!ReviewerEnum.PASS.getValue().equals(checkStatus)){
			User findUser = new User();
			Extend extend = new Extend();
			List<User> checkUserList = new ArrayList<>();
			if(RecordTypeEnum.OUT.getValue().equals(record.getType()) || RecordTypeEnum.IN.getValue().equals(record.getType())){
				extend.setExtendS1(VipUserTypeEnum.CHECK_USER.getValue());
				findUser.setExtend(extend);
				checkUserList = userService.findList(findUser);
			}
			if(RecordTypeEnum.RECHARGE.getValue().equals(record.getType()) || RecordTypeEnum.CHECKOUT.getValue().equals(record.getType())){
				extend.setExtendS1(VipUserTypeEnum.FINANCE.getValue());
				findUser.setExtend(extend);
				checkUserList = userService.findList(findUser);
			}
			if(checkUserList.size() > 0){
				for(User item : checkUserList){
					SMSUtils.sendingNotice(SMSUtils.SMS_TEMPLATE_ID_1,item.getMobile(),RecordTypeEnum.getRecordTypeName(record.getType()));
				}
			}
		}

		//不需要审核，发送通知给会员
		if(ReviewerEnum.PASS.getValue().equals(checkStatus)){
			SMSUtils.sendingNotice(SMSUtils.getTemplateIdForMember(record.getType()),member.getMobile(),
					record.getMoney().toString(),member.getBalance().toString());
		}
        return renderResult(Global.TRUE, text("操作成功！"+message));
    }


	/**
	 * 代理流水记录总列表
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = {"agentRecordList",""})
	public String agentRecord(Model model,Member member,String startTime,String endTime){
		//代理查看报表直接进入会员记录
		User currentUser = UserUtils.getUser();
		if (currentUser.getExtend()!=null){
			String postType = currentUser.getExtend().getExtendS1();
			if (VipUserTypeEnum.HEIGHT_AGENT.getValue().equals(postType)||
					VipUserTypeEnum.NORMAL_AGENT.getValue().equals(postType)||
					VipUserTypeEnum.VIP_AGENT.getValue().equals(postType)){
				//重定向
				return REDIRECT+"memberRecord?userCode="+currentUser.getUserCode()+"&startTime="+startTime+
						"&endTime="+endTime;
			}
		}
		model.addAttribute("member",member);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
			return "modules/mobile/agentRecordList";
		}
		return "modules/vip/agentRecordList";
	}


	/**
	 * 查询代理流水数据
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = "listAgentData")
	@ResponseBody
	public Page<AgentRecord> listAgentData(AgentRecord agentRecord, Model model,String exportCode,HttpServletRequest request, HttpServletResponse response) {
		Page page = new Page(request, response);
		//参数map
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("startTime",agentRecord.getStartTime());
		map.put("endTime",agentRecord.getEndTime());
		//设置分页参数
		agentRecord.setPage(page);
		page = memberService.findAgentRecordPage(map ,page);
		model.addAttribute("agentRecord",agentRecord);
		//导出
		if(exportCode!=null){
			String fileName = "代理报表数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			try(ExcelExport ee = new ExcelExport("代理报表数据", AgentRecord.class)){
				ee.setDataList(page.getList()).write(response, fileName);
			}
		}
		//统计数据
		String startTime = DateUtils.formatDate(agentRecord.getStartTime());
		String endTime = DateUtils.formatDate(agentRecord.getEndTime());
		HashMap<String,Object> countMap= recordService.countAllAgentRecordByDate(startTime,endTime);
		page.setOtherData(countMap);
		return page;
	}

	/**
	 * 所有会员流水帐页面
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = {"memberRecord", ""})
	public String memberRecord(String userCode,MemberRecord memberRecord,Model model) {
		String startTime = DateUtils.formatDate(memberRecord.getStartTime());
		String endTime = DateUtils.formatDate(memberRecord.getEndTime());
		userCode = StringUtils.isBlank(userCode) ? UserUtils.getUser().getUserCode() : userCode;
		model.addAttribute("userCode",userCode);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
			return "modules/mobile/memberRecord";
		}
		return "modules/vip/memberRecord";
	}


	/**
	 * 查询会员流水账列表
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = "memberRecordData")
	@ResponseBody
	public Page<Member> memberRecordData(String userCode, String exportCode,MemberRecord memberRecord,Model model, HttpServletRequest request, HttpServletResponse response) {
        Page page=new  Page(request, response);
        //参数map
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("startTime",memberRecord.getStartTime());
        map.put("endTime",memberRecord.getEndTime());
        map.put("userCode",userCode);
        //设置分页参数
        memberRecord.setPage(page);
        page = memberService.findMemberRecordPage(map,page);
//        page.setPageSize(page.getPageSize());
//        page.setCount(page.getList().size());
//        page.setPageNo(page.getPageNo());
        model.addAttribute("memberRecord",memberRecord);
		//导出
		if(exportCode!=null){
			String fileName = "会员报表数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			try(ExcelExport ee = new ExcelExport("会员报表数据", MemberRecord.class)){
				ee.setDataList(page.getList()).write(response, fileName);
			}
		}
		//统计数据
		String startTime = DateUtils.formatDate(memberRecord.getStartTime());
		String endTime = DateUtils.formatDate(memberRecord.getEndTime());
		userCode = StringUtils.isBlank(userCode) ? UserUtils.getUser().getUserCode() : userCode;
		HashMap<String,Object> countMap= recordService.countAgentRecordByDateAndAgentId(startTime,endTime,userCode);
		page.setOtherData(countMap);
        return page;
	}



	/**
	 * 查询列表
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = {"memberPersonRecord", ""})
	public String memberPersonRecord(Record record,String startTime,String endTime, Model model) {
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("record", record);
		//统计信息
		if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
			return "modules/mobile/memberPersonRecord";
		}
		return "modules/vip/memberPersonRecord";
	}

	/**
	 * 查询会员流水账列表
	 */
	@RequiresPermissions("vip:record:view")
	@RequestMapping(value = "memberPersonRecordData")
	@ResponseBody
	public Page<Record> personRecordData(Record record,String exportCode, HttpServletRequest request, HttpServletResponse response) {
		//只统计已审核
		record.setCreateDate_gte(record.getStartTime());
		record.setCreateDate_lte(record.getEndTime());
		record.setReviewerState(ReviewerEnum.PASS.getValue());
		Page page = recordService.findPage(new Page<Record>(request, response), record);
		//导出
		if(exportCode!=null){
			List<Record> list = RecordToExcelUtils.recordToModel(page.getList());
			String fileName = "会员详细报表数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			try(ExcelExport ee = new ExcelExport("会员详细报表数据", Record.class)){
				ee.setDataList(list).write(response, fileName);
			}
		}
		//统计数据
		String startTime = DateUtils.formatDate(record.getStartTime());
		String endTime = DateUtils.formatDate(record.getEndTime());
		HashMap<String,Object> countMap= recordService.countMemberRecordByDateAndMemberId(startTime,endTime,record.getMemberId());
		page.setOtherData(countMap);
		return page;
	}

    /**
     * 创建报表
     */
    @RequiresPermissions("vip:record:view")
    @RequestMapping(value = {"createReport", ""})
    public String createReport(){
        return "modules/vip/createReport";
    }

	/**
	 * 审核记录
	 */
	@ResponseBody
	@PostMapping(value = "checkRecord")
	@Transactional(rollbackFor = Exception.class)
	public String checkRecord(Record record) {
		String message = "操作成功！";
		if(RecordTypeEnum.getValue(Integer.parseInt(record.getReviewerState()))== null){
			return renderResult(Global.FALSE, "操作失败，检验数据不正确!");
		}
		User user = UserUtils.getUser();
		record.setReviewerId(user.getUserCode());
		if(record.getReviewerState().equals(ReviewerEnum.PASS.getValue())){
			//更新会员数据
			Member member = memberService.get(record.getMemberId());
			//出货  扣除余额、积分
			if(RecordTypeEnum.OUT.getValue().equals(record.getType())){
			    if(!UserUtils.getSubject().isPermitted("vip:check:out")){
                    return renderResult(Global.FALSE, "没有该权限");
                }
				member.setPoints(member.getPoints()-record.getMoney());
				member.setBalance(member.getBalance()-record.getMoney());
                member.setOutTotal(member.getOutTotal()+record.getMoney());
			}
			//入货  加余额、积分
			if(RecordTypeEnum.IN.getValue().equals(record.getType())){
			    if(!UserUtils.getSubject().isPermitted("vip:check:in")){
                    return renderResult(Global.FALSE, "没有该权限");
                }
				member.setPoints(member.getPoints()+record.getMoney());
				member.setBalance(member.getBalance()+record.getMoney());
                member.setInTotal(member.getInTotal()+record.getMoney());
			}
			//结账  余额、积分清零
			if(RecordTypeEnum.CHECKOUT.getValue().equals(record.getType())){
			    if(!UserUtils.getSubject().isPermitted("vip:check:checkout")){
                    return renderResult(Global.FALSE, "没有该权限");
                }
				member.setPoints(member.getBalance()-record.getMoney());
				member.setBalance(member.getBalance()-record.getMoney());
			}
			//充值  更改余额、积分、总充值
			if (RecordTypeEnum.RECHARGE.getValue().equals(record.getType())){
			    if(!UserUtils.getSubject().isPermitted("vip:check:recharge")){
                    return renderResult(Global.FALSE, "没有该权限");
                }
				member.setRechargeTotal(record.getMoney()+member.getRechargeTotal());
				member.setPoints(record.getMoney()+member.getPoints());
				member.setBalance(record.getMoney()+member.getBalance());
			}
			memberService.save(member);
		}
		recordService.save(record);
		//发送通知
		Member member = memberService.get(record.getMemberId());
		User agentUser = userService.get(member.getAgentId());
		if(record.getReviewerState().equals(ReviewerEnum.PASS.getValue())){
			//通知代理商
			SMSUtils.sendingNotice(SMSUtils.getTemplateId(record.getType()),agentUser.getMobile(),null);
			//通知会员
			SMSUtils.sendingNotice(SMSUtils.getTemplateIdForMember(record.getType()),member.getMobile(),
					record.getMoney().toString(),member.getBalance().toString());
		}else{
			SMSUtils.sendingNotice(SMSUtils.SMS_TEMPLATE_ID_2,agentUser.getMobile(),record.getRemarks());
		}
		return renderResult(Global.TRUE, message);
	}
}